// 通用函数
function formatPrice(price) {
    return '￥' + parseFloat(price).toFixed(2);
}

function formatDate(dateString) {
    const date = new Date(dateString);
    return date.toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
    });
}

// AJAX 请求处理
function handleAjaxError(error) {
    console.error('请求失败:', error);
    alert('操作失败，请稍后重试');
}

// 图片处理
function handleImageError(img) {
    img.onerror = null;
    img.src = '/farm/images/default-product.jpg';
}

// 表单处理
function validateForm(form) {
    const requiredFields = form.querySelectorAll('[required]');
    let isValid = true;
    
    requiredFields.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('is-invalid');
        } else {
            field.classList.remove('is-invalid');
        }
    });
    
    return isValid;
}

// 订单状态更新
function updateOrderStatus(orderId, status, successCallback) {
    $.post(`/farm/orders/${orderId}/status`, { status: status })
        .done(function(response) {
            if (response === 'success') {
                if (typeof successCallback === 'function') {
                    successCallback();
                }
            } else {
                alert('操作失败: ' + response);
            }
        })
        .fail(handleAjaxError);
}

// 文件上传预览
function previewImage(input, previewElement) {
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = function(e) {
            previewElement.src = e.target.result;
        };
        reader.readAsDataURL(input.files[0]);
    }
} 